/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.common.electricsent.service.impl;

import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.RecordSaveTypeEnum;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.punish.common.electricsent.dto.*;
import com.icinfo.cloud.provider.punish.common.electricsent.enums.DocumentSendStatusEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseQueryDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseDocumentRecordService;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.cloud.provider.punish.common.electricsent.enums.SendWayEnum;
import com.icinfo.cloud.provider.punish.common.electricsent.mapper.DocumentSendRecordMapper;
import com.icinfo.cloud.provider.punish.common.electricsent.model.DocumentSendRecord;
import com.icinfo.cloud.provider.punish.common.electricsent.model.DocumentSentRegister;
import com.icinfo.cloud.provider.punish.common.electricsent.service.IDocumentSendRecordService;
import com.icinfo.cloud.provider.punish.common.electricsent.service.IDocumentSentFlowService;
import com.icinfo.cloud.provider.punish.common.electricsent.vo.DocumentSendRecordVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartiesReasonTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICasePartiesRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainInfoVo;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * 描述: 文书发送记录 document_send_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年02月18日
 */
@Service
@Slf4j
public class DocumentSendRecordServiceImpl extends MyBatisServiceSupport implements IDocumentSendRecordService {
    @Resource
    private DocumentSendRecordMapper documentSendRecordMapper;
    @Resource
    private IDocumentSentFlowService documentSentFlowService;
    @Resource
    private ICaseMainInfoService caseMainInfoService;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;
    @Resource
    private ICaseDocumentRecordService caseDocumentRecordService;

    /**
     * 【V1.0.0】描述：保存文书发送记录
     *
     * @param saveDto {@link DocumentSendRecordSaveDto}
     * @return {@link Result <String>} 保存结果
     * @author xiangyuyu
     * @date 2022-02-16 16:02
     */
    @Override
    public Map<String,Object> saveDocumentSendRecord(DocumentSendRecordSaveDto saveDto) {
        String operateType = saveDto.getOperateType();
        Map<String, Object> resultMap = new HashMap<>(20);
        if(!RecordSaveTypeEnum.isLegalEnumCode(operateType)){
            throw new BusinessException("请指定有效的操作类型(1-新增/2-修改)");
        }
        DocumentSendRecord documentSendRecord = new DocumentSendRecord();
        if (!ObjectUtils.isEmpty(saveDto)) {
            BeanUtils.copyProperties(saveDto, documentSendRecord);
        }
        UserDTO userInfo = UserUtil.getUserInfo();
        if (!ObjectUtils.isEmpty(userInfo)) {
            saveDto.setSenderId(userInfo.getUserId() + "");
            saveDto.setSenderRealName(userInfo.getRealName());
        } else {
            saveDto.setSenderId("system");
            saveDto.setSenderRealName("管理员");
        }
        String recordSaveType = saveDto.getOperateType();
        String realPlaceSentType = saveDto.getRealPlaceSentType();
        String id;
        try {
            if (RecordSaveTypeEnum.MOD.getCode().equals(recordSaveType)) {
                id = saveDto.getId();
                if (ObjectUtils.isEmpty(id)) {
                    resultMap.put("success","false");
                    resultMap.put("msg",Constant.STRING_NO_PRIMARY_KEY);
                    return resultMap;
                } else {
                    DocumentSendRecordVo vo = getDocumentSendRecord(id);
                    if (ObjectUtils.isEmpty(vo)) {
                        resultMap.put("success","false");
                        resultMap.put("msg","未匹配到文书发送记录");
                        return resultMap;
                    }
                    Example updateE = new Example(DocumentSentRegister.class);
                    updateE.createCriteria().andEqualTo("id", id);
                    String partyId = documentSendRecord.getPartyId();
                    if(ObjectUtils.isEmpty(partyId)){
                        documentSendRecord.setPartyId(null);
                    }
                    documentSendRecordMapper.updateByExampleSelective(documentSendRecord, updateE);
                }
            } else {
                /*if (!Constant.STRING_1.equals(saveDto.getDataSource())
                        || (Constant.STRING_1.equals(saveDto.getDataSource()) && RealPlaceSentTypeEnum.YJQS.getCode().equals(realPlaceSentType))) {*/
                    id = BaseUtil.createUid();
                    documentSendRecord.setId(id);
                    documentSendRecordMapper.insertSelective(documentSendRecord);
               // }
                String sentWay = saveDto.getSentWay();
                if(SendWayEnum.TEXT_MSG.getCode().equals(sentWay)){
                    String caseId = saveDto.getCaseId();
                    CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
                    //排除简易程序，没有审批流程，无需流程滚动
                    if (!CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())) {
                        SentFlowRollInfoSaveDto sendFlowRollInfo = new SentFlowRollInfoSaveDto();

                        String partyId = saveDto.getPartyId();
                        //如果是非多当事人，送达滚动去掉当事人id

                        String partiesReasonType = caseMainInfo.getCasePartiesReasonType();
                        sendFlowRollInfo.setPartyId(partyId);
                        sendFlowRollInfo.setDocumentCatalogCode(saveDto.getDocumentCatalogCode());
                        if(!PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(partiesReasonType)){
                            sendFlowRollInfo.setPartyId(null);
                        }
                        sendFlowRollInfo.setCaseId(caseId);
                        resultMap = documentSentFlowService.sentFlowRoll(sendFlowRollInfo);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().contains(Constant.STRING_DUPLICATE_ENTRY) ||
                    e.getMessage().contains(Constant.STRING_DUPLICATE_ENTRY_LOWER)) {
                throw new BusinessException("请勿重复添加");
            } else {
                throw e;
            }
        }
        resultMap.put("success","true");
        resultMap.put("msg","成功！");
        return resultMap;
    }


    /**
     * 【V1.0.0】描述：获取文书发送记录列表
     *
     * @param queryDto {@link DocumentSendRecordQueryDto}
     * @return {@link List<DocumentSendRecordVo>} 文书发送记录列表
     * @author xiangyuyu
     * @date 2022-02-16 16:02
     */
    @Override
    public List<DocumentSendRecordVo> getDocumentSendRecordList(DocumentSendRecordQueryDto queryDto) {
        List<DocumentSendRecordVo> documentSendRecordList = documentSendRecordMapper.selectDocumentSendRecordList(queryDto);
        documentSendRecordList.forEach(e -> {
            e.setSentWayName(SendWayEnum.getValueByCode(e.getSentWayId()));
        });
        return documentSendRecordList;
    }

    /**
     * 【V1.0.0】描述：根据唯一标识查询文书发送记录
     *
     * @param id 唯一标识
     * @return {@link DocumentSendRecordVo} 文书发送记录
     * @author xiangyuyu
     * @date 2022-02-16 16:02
     */
    @Override
    public DocumentSendRecordVo getDocumentSendRecord(String id) {
        if (ObjectUtils.isEmpty(id)) {
            throw new BusinessException("未指定主键id");
        }
        DocumentSendRecord record = documentSendRecordMapper.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(record)) {
            throw new BusinessException("未匹配到文书发送记录");
        }
        DocumentSendRecordVo vo = new DocumentSendRecordVo();
        BeanUtils.copyProperties(record, vo);
        return vo;
    }

    /**
     * 【V2.0.0】描述：清空指定条件的发送记录
     *
     * @param condition 指定条件
     * @return int 删除记录数
     * @author xiangyuyu
     * @date 2022-05-16 10:39
     */
    @Override
    public int deleteRecordBySpecialCondition(Map<String, String> condition) {
        log.info("deleteRecordBySpecialCondition start ... condition:{}",condition);
        Example deleteExample = new Example(DocumentSendRecord.class);
        Example.Criteria  ec = deleteExample.createCriteria();
        condition.entrySet().forEach(e->{
            String k = e.getKey();
            String v = e.getValue();
            ec.andEqualTo(k,v);
        });
        DocumentSendRecord deleteRecord = new DocumentSendRecord();
        deleteRecord.setIsDelete(YesOrNoEnum.YES.getCode());
        int count = documentSendRecordMapper.updateByExampleSelective(deleteRecord,deleteExample);
        log.info("deleteRecordBySpecialCondition end ... count:{}",count);
        return count;
    }

    /**
     * 【V1.3.0】描述：修改文书送达记录为删除
     * @author tianrunjia
     * @date 2022-06-27
     * @return
     */
    @Override
    public void doRemoveDocumentSendRecord(String documentId, String caseId) {
        documentSendRecordMapper.deleteDocumentSendRecord(documentId,caseId);
    }

    @Override
    public Map<String,Object> saveExecuteDocumentSendRecord(DocumentSendRecordSaveDto saveDto) {
        String operateType = saveDto.getOperateType();
        Map<String, Object> resultMap = new HashMap<>(20);
        if(!RecordSaveTypeEnum.isLegalEnumCode(operateType)){
            throw new BusinessException("请指定有效的操作类型(1-新增/2-修改)");
        }
        DocumentSendRecord documentSendRecord = new DocumentSendRecord();
        if (!ObjectUtils.isEmpty(saveDto)) {
            BeanUtils.copyProperties(saveDto, documentSendRecord);
        }
        UserDTO userInfo = UserUtil.getUserInfo();
        if (!ObjectUtils.isEmpty(userInfo)) {
            saveDto.setSenderId(userInfo.getUserId() + "");
            saveDto.setSenderRealName(userInfo.getRealName());
        } else {
            saveDto.setSenderId("system");
            saveDto.setSenderRealName("管理员");
        }
        String recordSaveType = saveDto.getOperateType();
        String realPlaceSentType = saveDto.getRealPlaceSentType();
        String id;
        try {
            if (RecordSaveTypeEnum.MOD.getCode().equals(recordSaveType)) {
                id = saveDto.getId();
                if (ObjectUtils.isEmpty(id)) {
                    resultMap.put("success","false");
                    resultMap.put("msg",Constant.STRING_NO_PRIMARY_KEY);
                    return resultMap;
                } else {
                    DocumentSendRecordVo vo = getDocumentSendRecord(id);
                    if (ObjectUtils.isEmpty(vo)) {
                        resultMap.put("success","false");
                        resultMap.put("msg","未匹配到文书发送记录");
                        return resultMap;
                    }
                    Example updateE = new Example(DocumentSentRegister.class);
                    updateE.createCriteria().andEqualTo("id", id);
                    String partyId = documentSendRecord.getPartyId();
                    if(ObjectUtils.isEmpty(partyId)){
                        documentSendRecord.setPartyId(null);
                    }
                    documentSendRecordMapper.updateByExampleSelective(documentSendRecord, updateE);
                }
            } else {
                /*if (!Constant.STRING_1.equals(saveDto.getDataSource())
                        || (Constant.STRING_1.equals(saveDto.getDataSource()) && RealPlaceSentTypeEnum.YJQS.getCode().equals(realPlaceSentType))) {*/
                id = BaseUtil.createUid();
                documentSendRecord.setId(id);
                documentSendRecordMapper.insertSelective(documentSendRecord);
                // }
                String sentWay = saveDto.getSentWay();
                if(SendWayEnum.TEXT_MSG.getCode().equals(sentWay)){
                    String caseId = saveDto.getCaseId();
                    /*CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
                    //排除简易程序，没有审批流程，无需流程滚动
                    if (!CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())) {
                        SentFlowRollInfoSaveDto sendFlowRollInfo = new SentFlowRollInfoSaveDto();

                        String partyId = saveDto.getPartyId();
                        //如果是非多当事人，送达滚动去掉当事人id

                        String partiesReasonType = caseMainInfo.getCasePartiesReasonType();
                        sendFlowRollInfo.setPartyId(partyId);
                        sendFlowRollInfo.setDocumentCatalogCode(saveDto.getDocumentCatalogCode());
                        if(!PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(partiesReasonType)){
                            sendFlowRollInfo.setPartyId(null);
                        }
                        sendFlowRollInfo.setCaseId(caseId);
                        resultMap = documentSentFlowService.sentFlowRoll(sendFlowRollInfo);
                    }*/
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().contains(Constant.STRING_DUPLICATE_ENTRY) ||
                    e.getMessage().contains(Constant.STRING_DUPLICATE_ENTRY_LOWER)) {
                throw new BusinessException("请勿重复添加");
            } else {
                throw e;
            }
        }
        resultMap.put("success","true");
        resultMap.put("msg","成功！");
        return resultMap;
    }

    /**
     * 电子送达记录分页查询
     *
     * @param queryDto {@link DocumentSendPageRequest}
     * @return {@link Result<List<DocumentSendPageResponse>>} 电子送达记录列表
     * @author yehaufei
     * @date 2022-11-28
     */
    @Override
    public List<DocumentSendPageResponse> getDocumentSendList(DocumentSendPageRequest queryDto) {
        //机构判断
        checkOrgCode(queryDto);
        PageHelper.startPage(queryDto.getPageNum(),queryDto.getLength());
        List<DocumentSendPageResponse> list = documentSendRecordMapper.getDocumentSendList(queryDto);
        list.forEach(e -> {
            e.setSentWay(SendWayEnum.getValueByCode(e.getSentWay()));
            e.setSendStatus(DocumentSendStatusEnum.getValueByCode(e.getSendStatus()));
            e.setSDHZDocumentUrl(documentSendRecordMapper.getSDHZDocumentDoc(e.getCaseId(),e.getPartyId(),e.getCaseStageCode()));
        });
        return list;
    }

    /**
     * orgCode处理
     *
     * @param queryDto
     * @return void
     * @author lxj
     * @date 2022/3/31
     **/
    private void checkOrgCode(DocumentSendPageRequest queryDto) {
        queryDto.setOrg(0);
        if (StringUtils.isEmpty(queryDto.getOrgCode())) {
            return;
        }
        List<String> orgCodeList = new ArrayList<>();
        List<String> deptCodeList = new ArrayList<>();
        String[] str = queryDto.getOrgCode().split(",");

        for (String s : str) {
            if(s.indexOf("_")>0){
                orgCodeList.add(s);
            }else {
                orgCodeList.add(s);
            }
        }
        if(orgCodeList.size()>0&&deptCodeList.size()>0){
            queryDto.setOrg(1);
        }else if(orgCodeList.size()>0){
            queryDto.setOrg(2);
        }else if(deptCodeList.size()>0){
            queryDto.setOrg(3);
        }

        queryDto.setOrgCodeList(orgCodeList);
        queryDto.setDeptCodeList(deptCodeList);
    }
}
